import React, { Component } from 'react';
import { Modal, Button, Pagination, Upload, message } from 'antd';

import QMFetch from 'fetch';
import filter from 'util/filter';

import { QMConst } from 'qm-ux';

import NoData from 'uikit/no-data';
import { MassUpload } from 'uikit/mass-input';

import selectedImg from '../../style/imgs/selected.png';

export default class Material extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      type: 'image',
      selected: null,
      params: {
        page: 1,
        pageSize: 9
      },
      data: {
        item: [],
        total_count: 0
      }
    };
  }

  render() {
    let { show, selected, params, type = 'image', data } = this.state,
      titles = {
        news: '我的图文',
        adv: '我的高级图文',
        image: '我的图片',
        voice: '我的语音',
        video: '我的视频'
      };

    return (
      <Modal
        className="material"
        title={titles[type]}
        visible={show}
        width={800}
        onOk={() => this._ok(selected)}
        onCancel={this.close}
      >
        <div className="btns">
          {['news', 'adv', 'image'].includes(type) &&
            {
              news: (
                <Button
                  type="primary"
                  style={{ fontSize: 14 + 'px' }}
                  icon="upload"
                  onClick={() => this._go('/news/news')}
                >
                  新建图文
                </Button>
              ),
              adv: (
                <Button
                  type="primary"
                  style={{ fontSize: 14 + 'px' }}
                  icon="upload"
                  onClick={() => this._go('/news/adNews')}
                >
                  新建高级图文
                </Button>
              ),
              image: (
                <Upload
                  action={`${QMConst.HOST['v_wx_api']}/api/material/upload`}
                  showUploadList={false}
                  withCredentials={true}
                  accept="image/*"
                  name="media"
                  data={{ type: 'image' }}
                  onChange={({ file: { response } }) => {
                    response && (this.setState({ selected: response }), this._paging(1));
                  }}
                  beforeUpload={file => {
                    let fileExt = 'bmp/png/jpeg/jpg/gif';
                    let maxSize = 2 * 1024 * 1024;
                    let { name, size } = file;
                    let fileType = name.split('.')[1];
                    if (!fileExt.includes(fileType.toLocaleLowerCase())) {
                      message.warn(`${type}格式不支持${fileType}`);
                      return false;
                    }
                    if (maxSize && size > maxSize) {
                      message.warn(`图片大小超过${maxSize / 1024 / 1024}M`);
                      return false;
                    }
                    return true;
                  }}
                >
                  <Button type="primary" style={{ fontSize: 14 + 'px' }} icon="upload">上传图片</Button>
                </Upload>
              )
            }[type]}
        </div>
        {data.total_count
          ? <div className={`material-${type}`}>
              {data.item.map(o => {
                let key = { adv: 'id' }[type] || 'media_id',
                  isSelected = o[key] === (selected || {})[key];
                return {
                  news: <News data={o} isSelected={isSelected} onSelect={this._select} />,
                  adv: <Adv data={o} isSelected={isSelected} onSelect={this._select} />,
                  image: <Image data={o} isSelected={isSelected} onSelect={this._select} onDelete={this._paging} />,
                  voice: <div>音频</div>,
                  video: <div>视频</div>
                }[type];
              })}
            </div>
          : <NoData />}
        <Pagination
          current={params.page}
          pageSize={params.pageSize}
          defaultCurrent={params.page}
          defaultPageSize={params.pageSize}
          total={data.total_count}
          onChange={this._paging}
          showQuickJumper
        />
      </Modal>
    );
  }

  _go = url => {
    location.hash = location.hash.replace(/^#\/[^\?]*(\??.*)$/gm, url + '$1');
  };

  _select = e => {
    this.setState({ selected: e === this.state.selected ? null : e });
  };

  _paging = (page = this.state.params.page, pageSize = this.state.params.pageSize) => {
    setTimeout(async () => {
      let { type, params } = this.state;
      Object.assign(params, { page, pageSize });
      this.setState({
        params,
        show: true,
        data: await QMFetch({
          url: type === 'adv' ? 'api/advancedNews/list' : `api/material/list/${type}`,
          body: params
        })
      });
    }, 1);
  };

  open = (type, selected) => {
    let { params } = this.state;
    params.pageSize = { news: 9, adv: 9, image: 12 }[type];
    this.setState({ type, selected, params });
    this._paging(1);
  };

  close = () => {
    this.setState({ show: false });
  };

  _ok = selected => {
    let { onSelect = () => {} } = this.props;
    onSelect(selected);
    this.setState({ show: false });
  };
}

export class News extends Component {
  render() {
    let { isSelected, data = { content: {} }, onSelect = () => {} } = this.props;

    return (
      <div className={`material-item${isSelected ? ' selected' : ''}`} onClick={() => onSelect(data)}>
        <img className="material-selected" src={selectedImg} />
        <p>{filter.date(data.content.update_time * 1000)}</p>
        {data.content.news_item.map((o, i) =>
          <div className={i === 0 ? '' : 'small'}>
            <h3>{o.title}</h3>
            <img src={o.thumb_url} width="100%" />
            <p>{o.digest}</p>
          </div>
        )}
      </div>
    );
  }
}

export class Adv extends Component {
  render() {
    let { isSelected, data, onSelect = () => {} } = this.props;

    return (
      <div className={`material-item${isSelected ? ' selected' : ''}`} onClick={() => onSelect(data)}>
        <img className="material-selected" src={selectedImg} />
        <p>{filter.date(data.updatedAt)}</p>
        {data.articles.map((o, i) =>
          <div className={i === 0 ? '' : 'small'}>
            <h3>{o.title}</h3>
            <img src={o.thumb_url} width="100%" />
            <p>{o.digest}</p>
          </div>
        )}
      </div>
    );
  }
}

export class Image extends Component {
  render() {
    let { isSelected, data, onSelect = () => {} } = this.props,
      style = { backgroundImage: `url("${data.url}")` };

    return (
      <div className={`material-item${isSelected ? ' selected' : ''}`} onClick={() => onSelect(data)}>
        <img className="material-selected" src={selectedImg} />
        <div style={style} />
        <p>{this._dealName(data.name)}</p>
        {/*<p>*/}
        {/*<Button type="primary" size="small" onClick={this._delete}>删除</Button>*/}
        {/*</p>*/}
      </div>
    );
  }

  _dealName = name => {
    let ns = name.split(/-|\./g);
    let timeStr = ns[ns.length - 2];
    if (typeof parseInt(timeStr) === 'number' && (parseInt(timeStr) + '').length === 13) {
      name = name.replace(`-${timeStr}`, '');
    }
    return name;
  };

  _delete = () => {
    Modal.confirm({
      title: '确认删除这张图片吗？',
      content: '删除后将不可恢复',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        let { data, isSelected } = this.props;
        QMFetch({
          host: QMConst.HOST['v_wx_api'],
          method: 'POST',
          url: `api/material/${data.media_id}/delete`
        }).then(() => {
          isSelected && this.setState({ selected: null });
          this.props.onDelete && this.props.onDelete();
        });
      }
    });
  };
}
